// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {globalConfig} from "../config/globalConfig";
import EverydaySignItem, {SignItem} from "./everydaySignItem";
import {getReward} from "../config/config";
import * as config from "../config/config";
import {apiUtils} from "../web/api/ApiUtils";
import {model} from "../web/model/Model";
import {utils} from "../utils/utils";
import {wxUtils} from "../wx/wxUtils";

const {ccclass, property} = cc._decorator;

@ccclass
export default class EveryDaySign extends cc.Component {
  // LIFE-CYCLE CALLBACKS:

  @property(cc.Node)
  signLayers: cc.Node = null

  @property(cc.Node)
  root: cc.Node = null;

  onLoad() {
    this.refreshNode();
  }

  refreshNode() {
    globalConfig.signin.forEach((value: any, index: number) => {
      let itemId = config.getReward(value.reward, 'itemid');
      let num = config.getReward(value.reward, 'number');
      let itemName: string = config.getItem(itemId, 'name');
      let itemType: number = config.getItem(itemId, 'type');
      let iconId = config.getItem(itemId, 'iconid');

      const item = this.signLayers.children[index].getComponent(EverydaySignItem);
      item.data = {
        index: index,
        icon: iconId,
        name: itemName,
        itemType: itemType,
        num, num
      }
      item.node.on(cc.Node.EventType.TOUCH_START, this.onItemNode, this)
    })
  }

  onItemNode(e: cc.Event.EventTouch) {
    const item = e.getCurrentTarget().getComponent(EverydaySignItem)
    if (item.state === SignItem.SIGNABLE) {
      apiUtils.sign();
      model.commonResult.onceSuccess(() => {
        model.user.isSignToday = true;
        model.user.signCounts = model.user.signCounts + 1;
        this.refreshNode();
      })
    }
  }

  onClose() {
    utils.dialogClose(this.node, this.root)
    wxUtils.showMenuAd()
  }

}
